<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
// ajax  post方法封装



// 利用对象传值，参数不需要一一对应。
    post({
        data:"user=123&pwd=a123",
        ansync:true,
        dataType:"json",
        url:"../../day23/php/post.php",
        success: function(result) {
            console.log(result);
        }
    });

    post({
        data:{
            user:"123",
            pwd:"a123",
        },
        ansync:true,
        dataType:"json",
        url:"../../day23/php/post.php",
        success: function(result) {
            console.log(result);
        }
    });

// 回调函数   =>   把函数当成参数传到另一个函数中
    function post({url = "",data = "",async = true,dataType = "text",success} = {}) {
        var xhr = new XMLHttpRequest();

        if(typeof data == "object") {
            var str = "";
            for (var key in data) {
                str += key + "=" + data[key] + "&"      // 进行拼接
            }
            data = str.substring(0,str.length-1)    // 去除最后多余的 &
        }

        xhr.open("post", url, async);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data);

        xhr.onreadystatechange = function() {
            if(xhr.status == 200 && xhr.readyState == 4) {
                var result =  xhr.responseText;  //默认返回响应文本
                if(dataType == "json") {  // 如果是json类型就转为json对象 
                    result = JSON.parse(xhr.responseText);
                }

                if(success) {       // 如果有回调函数，执行回调函数         并把请求的结果作为实际参数传入
                    success(result);
                }    
                 
            }
        }
    }
</script>
</html>